package cn.wx.autoconfiguration;

import cn.wx.WxPayServiceRegisterPostProcessor;
import cn.wx.api.WxPayMultipleService;
import cn.wx.api.impl.WxPayMultipleServiceImpl;
import cn.wx.common.configuration.WxConfiguration;
import cn.wx.properties.WxPayProperties;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;

import static cn.wx.properties.WxPayProperties.PREFIX;

/**
 * 微信支付自动配置
 */
@Import(WxConfiguration.class)
@EnableConfigurationProperties(WxPayProperties.class)
@ConditionalOnClass(WxPayService.class)
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", matchIfMissing = true)
public class WxPayAutoConfiguration {

    private final WxPayProperties properties;


    public WxPayAutoConfiguration(WxPayProperties properties) {
        this.properties = properties;
    }

    /**
     * 构造微信支付服务对象.
     *
     * @return 微信支付service
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean
    public WxPayMultipleService wxPayMultipleService() {
        properties.verification(PREFIX);
        return new WxPayMultipleServiceImpl(properties.getName());
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxPayServiceRegisterPostProcessor")
    public WxPayServiceRegisterPostProcessor wxPayServiceRegisterPostProcessor() {
        return new WxPayServiceRegisterPostProcessor(properties);
    }

}
